TARGET    := led-blink

# 存放构建时生成的文件的目录
BUILD_DIR := ./Build

# ARM GCC 工具链
TOOLCHAIN  = arm-none-eabi-
CC  := $(TOOLCHAIN)gcc
CP  := $(TOOLCHAIN)objcopy
AS  := $(TOOLCHAIN)gcc -x assembler-with-cpp
SZ  := $(TOOLCHAIN)size
HEX := $(CP) -O ihex
BIN := $(CP) -O binary -S




############################################# HAL 库源码 ###################################################
ASM_SRC := ./Drivers/CMSIS/Device/ST/STM32F1xx/Source/Templates/gcc/startup_stm32f103xe.s
C_SRC   := ./Drivers/CMSIS/Device/ST/STM32F1xx/Source/Templates/system_stm32f1xx.c
C_SRC   += $(wildcard ./Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal*.c)
C_SRC   += ./Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_ll_usb.c
C_SRC   += ./Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_ll_sdmmc.c
C_SRC   += ./Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_ll_fsmc.c
C_SRC   := $(filter-out %template.c, $(C_SRC))

############################################# 头文件路径 ###################################################
INC_DIR := ./Drivers/CMSIS/Include/
INC_DIR += ./Drivers/CMSIS/Device/ST/STM32F1xx/Include/
INC_DIR += ./Drivers/STM32F1xx_HAL_Driver/Inc/
INC_DIR += ./User/
INC_DIR += ./User/led/

############################################## 用户源码 ####################################################
C_SRC += $(wildcard ./User/*.c)
C_SRC += $(wildcard ./User/led/*.c)




# 内核架构
CPU := cortex-m3
# 预定义宏
DEFS := -D USE_HAL_DRIVER -D STM32F103xE
# 链接脚本
LINK_SCRIPT := ./STM32F103ZETx_FLASH.ld
# 编译参数
CP_FLAGS := $(DEFS) $(addprefix -I,$(INC_DIR)) -mcpu=$(CPU) -g -gdwarf-2 -mthumb -Os -Wall -Wextra -fdata-sections -ffunction-sections -fmessage-length=0 -MMD -MP 
# 汇编参数
AS_FLAGS := $(CP_FLAGS)
# 链接参数
LD_FLAGS := -mcpu=$(CPU) -T $(LINK_SCRIPT) -specs=nano.specs -Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref,--gc-sections,--print-memory-usage




# 设置文件搜索路径，.h 文件路径由 gcc -I 参数指定
vpath %.c $(sort $(dir $(C_SRC)))
vpath %.s $(sort $(dir $(ASM_SRC)))
# 保留 .o 文件，make 可能会删除生成的 .o 文件
.PRECIOUS: $(BUILD_DIR)/%.o




.PHONY: all
all: $(BUILD_DIR) $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).bin $(BUILD_DIR)/$(TARGET).hex
	@echo "Done"

%.elf: $(addprefix $(BUILD_DIR)/,$(notdir $(C_SRC:.c=.o))) $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SRC:.s=.o)))
	$(CC) $(LD_FLAGS) $^ -o $@

$(BUILD_DIR)/%.o: %.c
	$(CC) -c $(CP_FLAGS) $< -o $@

$(BUILD_DIR)/%.o: %.s
	$(AS) -c $(AS_FLAGS) $< -o $@

%.hex: %.elf
	$(HEX) $< $@

%.bin: %.elf
	$(BIN) $< $@

$(BUILD_DIR):
	mkdir -p $@




clean:
	rm $(BUILD_DIR)/ -rf

st-flash: $(BUILD_DIR)/$(TARGET).bin
	st-flash --format binary write $(BUILD_DIR)/$(TARGET).bin 0x8000000

st-erase:
	st-flash erase

isp-flash: $(BUILD_DIR)/$(TARGET).bin
	stm32flash -b 115200 -i '-dtr&rts,dtr:-dtr&-rts,dtr' -v -w $(BUILD_DIR)/$(TARGET).bin /dev/ttyUSB0

isp-erase:
	stm32flash -b 115200 -i '-dtr&rts,dtr:-dtr&-rts,dtr' -o /dev/ttyUSB0

isp-info:
	stm32flash -b 115200 -i '-dtr&rts,dtr:-dtr&-rts,dtr' /dev/ttyUSB0

rebuild: clean all

install: st-flash




# 包含由 gcc -MMD 参数生成的 .d 文件
-include $(BUILD_DIR)/*.d
